package com.lbc.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//  线程创建三：实现callable接口
/*
callable的好处
1.可以定义返回值
2.可以抛出异常
 */
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public TestCallable (String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://t7.baidu.com/it/u=3616242789,1098670747&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1604305362&t=1a625b5defe8f755e4594fc452b3ed42", "D:\\aaa\\1.jpg");
        TestCallable t2 = new TestCallable("https://t8.baidu.com/it/u=1484500186,1503043093&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1604305362&t=3f21340aa82abfc291ff2b83709fd2d2", "D:\\aaa\\2.jpg");
        TestCallable t3 = new TestCallable("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=16207085,969658569&fm=26&gp=0.jpg", "D:\\aaa\\3.jpg");

        //  创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //  提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //  获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        //  关闭服务
        ser.shutdownNow();
    }

}

//  下载器
class WebDownloader {
    //  下载方法
    public void downloader (String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }

}